Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Lists

Looping List items

Lists in Python are powerful because you can efficiently iterate through their elements using loops. Here's a breakdown of the primary methods for looping and iterating:

1. The Classic for Loop

The for loop is the most fundamental way to iterate through each element in a list. It assigns the current element to a variable in each iteration.
Iterating list using for loop in python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Output

apple banana cherry

2. Looping with Index (enumerate)

The enumerate function is helpful when you need both the element and its index in each iteration. It returns an enumerate object that yields tuples containing the index and the element.
Iterating or looping list using index in python numbers = [10, 20, 30] for i, number in enumerate(numbers): print(f"Index: {i}, Number: {number}")

Output

Index: 0, Number: 10 Index: 1, Number: 20 Index: 2, Number: 30

3. Looping in Reverse (reversed)

The reversed function returns an iterator that yields elements in reverse order.
Looping list in reverse in python colors = ["red", "green", "blue"] for color in reversed(colors): print(color)

Output

blue green red

4. List Comprehension with Looping Logic

While not strictly a looping construct, list comprehensions can incorporate looping logic to create new lists based on conditions.
Looping list and print elements in python numbers = [1, 2, 3, 4, 5] squared_numbers = [number * number for number in numbers] print(squared_numbers)

Output

[1, 4, 9, 16, 25]

5. while Loop (Less Common for Lists)

While for loops are preferred for iterating through lists in their entirety, while loops can be used for specific conditions.
Looping list using while loop in python shopping_list = ["bread", "milk", "eggs"] i = 0 while i < len(shopping_list): print(shopping_list[i]) i += 1

Output

bread milk eggs

Choosing the Right Method ✦ Simple iteration through elements: Use the classic for loop. ✦ Needing both element and index: Employ enumerate. ✦ Looping in reverse order: Utilize reversed. ✦ Creating a new list with transformations: Leverage list comprehensions (often more concise). ✦ Specific conditional iteration: Consider while loops (less common for simple list processing). Additional Considerations ✦ You can modify elements within the loop using their index or variable name assigned by the for loop. ✦ Be mindful of infinite loops if your loop condition is not carefully defined. ✦ Early termination: You can use break to exit the loop prematurely if a certain condition is met. ✦ Skipping elements: Use continue to skip the current iteration and proceed to the next one.

  📌TAGS

★python ★ list ★ methods

Tutorials